package pl.bizuteria.sklep.admin.client.activity.product;

import pl.bizuteria.sklep.admin.client.place.ProxyListPlace;
import pl.bizuteria.sklep.admin.client.ui.product.IProductEditView;
import pl.bizuteria.sklep.api.shared.request.ApplicationRequestFactory;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.gwt.client.RequestFactoryEditorDriver;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.RequestContext;

public abstract class EditActivity<P extends EntityProxy, V extends IProductEditView<P>>
		extends AbstractActivity implements IProductEditView.Presenter {
	protected IProductEditView<P> view;
	protected EventBus eventBus;
	protected PlaceController placeController;
	protected final RequestContext request;

	protected RequestFactoryEditorDriver<P, ? extends Editor<P>> driver;
	IRequestMixin<P> requestMixin;

	public EditActivity(IRequestMixin<P> requestMixin, IProductEditView<P> view, EventBus eventBus,
			PlaceController placeController, RequestContext request) {
				this.requestMixin = requestMixin;
				this.view = view;
				this.eventBus = eventBus;
				this.placeController = placeController;
				this.request = request;
	}

	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		panel.setWidget(view);
		view.setPresenter(this);
		driver = view.createEditorDriver();
		driver.edit(getProxy(), createSaveRequest(getProxy()));
	}

	protected abstract P getProxy();


	public void editClicked() {
		RequestContext requestContext = driver.flush();
		requestContext.fire(new Receiver<Void>() {

			@Override
			public void onSuccess(Void response) {
				placeController.goTo(getPlaceAfterEdit());
			}
		});
	}

	public void cancelClicked() {
		placeController.goTo(new ProxyListPlace(getProxy().stableId().getProxyClass()));
	}


	public Place getPlaceAfterEdit(){
		return new ProxyListPlace(getProxy().stableId().getProxyClass());
	}

	protected RequestContext createSaveRequest(P proxy){
		return requestMixin.createSaveRequest(proxy);
	}
	


}
